<?php
/**
 * Created by PhpStorm.
 * User: tommy
 * Date: 2018/6/13
 * Time: 14:09
 */

namespace backend\models;


use common\component\BaseModel;
use common\component\XxteaD;
use common\models\User;
use common\utils\CommonUtil;

class LoginForm extends BaseModel
{
    public $username;
    public $_user;

    public $password;

    public $csrf_token;

    public function rules()
    {
        return  [
            ['username','required','message'=>'请输入手机号码/邮箱'],
            [['username'],'trim'],


            [['password'],'required','message'=>'密码不能为空'],
            [['password'],'string','min' => 6,"tooShort"=>"请输入6位以上密码"],
            ['password','validatePassword']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'username' => '用户名',
            'password' => '密码',
        ];
    }

    public function validatePassword($attribute,$params) {
        if (!$this->hasErrors()){
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute,"用户名或密码错误");
            }
        }
    }


    public function login() {
        if ($this->validate()) {
            return \Yii::$app->user->login($this->getUser(),\Yii::$app->user->loginDuration);
        } else {
            return false;
        }
    }

    public function getUser() {
        if ($this->_user === null) {
            $this->_user = User::findByUsername($this->username);
        }
        return $this->_user;
    }
    public function actionLogout() {
        if (\Yii::$app->user->getIsGuest()) {
            return $this->goHome();
        }
        \Yii::$app->user->logout();
        return $this->goHome();
    }
}
